package com.shangguan.springboot.controller;

import com.google.gson.Gson;
import com.shangguan.springboot.dao.TUserMapper;
import com.shangguan.springboot.entity.TUser;
import com.shangguan.springboot.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @ClassName: UserController
 * @Description: 用户
 * @Author: 一尘
 * @Date: 2020 年 03 月 07 23:17
 * @Version 1.0
 */
@Slf4j
@Controller
public class UserController {
    @Autowired
    TUserMapper  tUserMapper;

    @PostMapping(value = "/doLogin" ,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String login(@RequestBody TUser user){
        log.info("------------用户信息------------------"+user);
        // 获取Subject
        Subject subject = SecurityUtils.getSubject();
        // 封装用户数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(),user.getUserPassword());
        AjaxResult  result = new AjaxResult();
        //执行登录方法
        try {
            log.info("------------用户开始进行验证------------------");
            subject.login(usernamePasswordToken);
            result.setSuccess(true);
            result.setMsg("用户登录成功!");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
              result.setSuccess(false);
              result.setMsg("用户名错误");
        }catch (IncorrectCredentialsException e){
            result.setSuccess(false);
            result.setMsg("密码错误");
        }
        Gson goson = new Gson();
        log.debug("------------用户登录验证结束------------------");
        return goson.toJson(result);
    }
    /*//退出登录
    @GetMapping("/logout")
    public String logout(SessionStatus sessionStatus){
          sessionStatus.setComplete();
          return "redirect:/login";
    }*/

    //退出登录
    @GetMapping("/logout")
    public Object logout(Map<String,Object> map){
        Subject  subject = SecurityUtils.getSubject();
        subject.logout();
        map.put("msg","退出登录");
        return map;
    }
}
